package NETWORK;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TcpServer {
     //服务器使用的socket
     private ServerSocket serverSocket = null;

     public TcpServer(int port) throws IOException {
         //创建服务端,用于接收TCP报文
         serverSocket = new ServerSocket(port);
     }

     //启动服务器
    public void start() throws IOException {
        System.out.println("服务器启动");
        while(true){//服务器长时间运行
            Socket clientSocket = serverSocket.accept();
            processConnection(clientSocket);
        }
    }
    private void processConnection(Socket clientSocket) throws IOException {
         System.out.printf("[%s : %d] 建立连接\n",clientSocket.getInetAddress().toString()
                 ,clientSocket.getPort());
         try(InputStream inputStream = clientSocket.getInputStream();
         OutputStream outputStream = clientSocket.getOutputStream()){
             Scanner scanner = new Scanner(inputStream);//用于接收数据
             PrintWriter printWriter = new PrintWriter(outputStream);//用于发送数据
             while(true){
                 if(!scanner.hasNext()){
                     //如果读到结束符就断开连接
                     System.out.printf("[%s : %d] 断开连接\n",clientSocket.getInetAddress().toString()
                             ,clientSocket.getPort());
                     break;
                 }
                 //接收请求并且解析
                 String request = scanner.next();
                 //根据请求做出响应==>回显
                 String response = process(request);
                 //将响应发送给客户端===>这里要发送时加上空格==>防止next阻塞
                 printWriter.println(response);
                 printWriter.flush();//不要忘记双薪缓冲区
                 System.out.printf("[%s : %d] 发送成功 req : %s ; rep : %s\n",clientSocket.getInetAddress().toString()
                         ,clientSocket.getPort(),request,response);
            }
         }catch(IOException e){
             e.printStackTrace();
         }finally {
             clientSocket.close();
         }
     }
     //回显服务器==>客户端做出什么请求就给什么样的响应
     public String process(String request){
         return request;
     }

    public static void main(String[] args) throws IOException {
        TcpServer tcpServer = new TcpServer(8000);
        tcpServer.start();
    }


}
